﻿Imports Microsoft.VisualBasic

Namespace WebApi
    Namespace Klout
        Public Class KloutClient

            Private webClient As WebApi.Net.WebClient

            Public Sub New(oauth2 As WebApi.Oauth.Oauth2)

                Me.webClient = New WebApi.Net.WebClient
                Me.webClient.oAuth2 = oauth2

            End Sub

            Public Property LastError As Net.ServiceError
            Private Function Download(address As String) As String

                Me.LastError = New Net.ServiceError With {
                    .webClient = Me.webClient,
                    .Net = WebApi.Type.KLOUT
                }

                Dim Res = ""
                Dim TryDonwload = 0
                Do
                    Try
                        Res = Encoding.UTF8.GetString(Me.webClient.DownloadData(address))
                        TryDonwload = 0

                    Catch ex As Exception

                        TryDonwload += 1

                        MyApp.WriteProcLog(SF("!!! CONNECT ERROR !!! errore n:{0} - {1} - {2}", TryDonwload, ex.Message, Me.webClient.RequestUri.AbsolutePath), MyApp.Task.TaskType.NET_CONNECT)

                        Me.LastError.ResError = "!!! CONNECT ERROR !!!"
                        Me.LastError.Code = -1
                        Me.LastError.Message = ex.Message

                    End Try

                    Select Case Me.webClient.StatusCode

                        Case 500, 502, 503, 504

                            TryDonwload += 1

                            MyApp.WriteProcLog(SF("!!! SERVER ERROR !!! errore n:{0} - {1} - {2}", TryDonwload, Res), MyApp.Task.TaskType.NET_API)

                            Me.LastError.ResError = Res
                            Me.LastError.Code = Me.webClient.StatusCode
                            Me.LastError.Message = Me.webClient.StatusCodeDescr

                    End Select

                    Select Case TryDonwload
                        Case 1
                            Threading.Thread.Sleep(2000)
                        Case 2
                            Threading.Thread.Sleep(10000)
                        Case 3
                            Threading.Thread.Sleep(20000)
                        Case 4
                            Threading.Thread.Sleep(60000)
                        Case Is > 4

                            If Me.LastError.Code < 0 Then
                                Net.ExceptionBase.ThrowException(New Net.ExceptionConnectionNetwork With {.ServiceError = Me.LastError})
                            Else
                                Net.ExceptionBase.ThrowException(New Net.ExceptionConnectionServer With {.ServiceError = Me.LastError})
                            End If

                    End Select


                Loop Until TryDonwload = 0

                webClient.postParams.Clear()
                webClient.Multipart = False

                If Me.webClient.StatusCode <> 200 Then

                    Me.LastError.ResError = Res


                    Try
                        Dim Err As ServiceError
                        Err = MyApp.JSONDeserializeObj(Of ServiceError)(Res)

                        Me.LastError.Code = Err.code
                        Me.LastError.Message = Err.message

                    Catch ex As Exception

                        Me.LastError.Code = Me.webClient.StatusCode
                        Me.LastError.Message = Res

                    End Try

                    'https://bufferapp.com/developers/api/errors
                    Select Case Me.webClient.StatusCode

                        Case 400
                            Net.ExceptionBase.ThrowException(New Net.ExceptionAPIResponse With {.ServiceError = Me.LastError})


                        Case 403
                            Net.ExceptionBase.ThrowException(New Net.ExceptionAPIAccount With {.ServiceError = Me.LastError})

                        Case 404
                            Net.ExceptionBase.ThrowException(New Net.ExceptionAPIResponse With {.ServiceError = Me.LastError})

                    End Select


                    'End Select

                    Net.ExceptionBase.ThrowException(New Net.ExceptionBase With {.ServiceError = Me.LastError})

                End If


                Return Res

            End Function


            Public Function GetIdentityTwitterId(id As String) As Identity

                Dim Uri As New UriBuilder(SF("http://api.klout.com/v2/identity.json/tw/{0}", id))

                Dim queryString = HttpUtility.ParseQueryString("")

                'queryString.Add("format", "json")

                Uri.Query = queryString.ToString

                Dim Res = Me.Download(Uri.Uri.AbsoluteUri)
                Return MyApp.JSONDeserializeObj(Of Identity)(Res)


            End Function

            Public Function GetShowUser(id As String) As User

                Dim Uri As New UriBuilder(SF("http://api.klout.com/v2/user.json/{0}", id))

                Dim queryString = HttpUtility.ParseQueryString("")

                'queryString.Add("format", "json")

                Uri.Query = queryString.ToString

                Dim Res = Me.Download(Uri.Uri.AbsoluteUri)
                Return MyApp.JSONDeserializeObj(Of User)(Res)


            End Function

            Public Function GetTopics(id As String) As List(Of Topic)

                Dim Uri As New UriBuilder(SF("http://api.klout.com/v2/user.json/{0}/topics", id))

                Dim queryString = HttpUtility.ParseQueryString("")

                'queryString.Add("format", "json")

                Uri.Query = queryString.ToString

                Dim Res = Me.Download(Uri.Uri.AbsoluteUri)
                Return MyApp.JSONDeserializeObj(Of List(Of Topic))(Res)


            End Function


        End Class
        Public Class ServiceError

            Public Property success As Boolean
            Public Property message As String
            Public Property code As Integer

        End Class
        Public Class Identity

            Public Property id As String
            Public Property network As String

        End Class


        Public Class User

            Public Property kloutId As String
            Public Property nick As String
            Public Property score As Score

        End Class
        Public Class Score

            Public Property score As Double
            Public Property bucket As String

        End Class
        Public Class ScoreDeltas

            Public Property dayChange As Double
            Public Property weekChange As Double
            Public Property monthChange As Double

        End Class

        Public Class Topic

            Public Property id As String
            Public Property displayName As String
            Public Property name As String
            Public Property slug As String

        End Class



        '        "kloutId": "635263",
        '"nick": "jtimberlake",
        '"score": {
        '    "score": 92.11237537491627,
        '    "bucket": "90-100"
        '},
        '"scoreDeltas": {
        '    "dayChange": 0.01661513817734317,
        '    "weekChange": -0.09185280944413421,
        '    "monthChange": -0.28369574423780364
        '}


    End Namespace
End Namespace


